package com.gxz.shardingreadwrite.api;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public final class DataSourceUtil {

    private static final String USER_NAME = "root";

    private static final String PASSWORD = "qwe123";

    private static DataSource createDataSource(String url) {
        DruidDataSource result = new DruidDataSource();
        result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
        result.setUrl(url);
        result.setUsername(USER_NAME);
        result.setPassword(PASSWORD);
        return result;
    }

    private static Map<String, DataSource> createDataSourceMap() {
        final Map<String, DataSource> result = new HashMap<>();
        result.put("master", DataSourceUtil.createDataSource(
            "jdbc:mysql://124.223.73.168:13306/rw_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"));
        result.put("slave", DataSourceUtil.createDataSource(
            "jdbc:mysql://101.33.250.161:13306/rw_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"));
        return result;
    }

    public static DataSource getMasterSlaveDataSource() throws SQLException {
        MasterSlaveRuleConfiguration masterSlaveRuleConfig =
            new MasterSlaveRuleConfiguration("ds_master_slave", "master", Collections.singletonList("slave"));
        return MasterSlaveDataSourceFactory.createDataSource(createDataSourceMap(), masterSlaveRuleConfig,
            new Properties());
    }
}